/*
 * hoolog.c
 *
 *  Created on: Apr 13, 2012
 *      Author: benoybose
 */

#include "hclog.h"
#include <time.h>
#include <stdlib.h>
#include <stdarg.h>


FILE* pLogFile = 0;

const int HOO_LOG_LEVEL_ERROR = 0;
const int HOO_LOG_LEVEL_DEBUG = 1;
const int HOO_LOG_LEVEL_INFO = 3;

const char* HOO_LOG_ERROR_TEXT = "Error";
const char* HOO_LOG_DEBUG_TEXT = "Debug";
const char* HOO_LOG_INFO_TEXT = "Information";

const char* HOO_LOG_LEVELS[3];

void hclog_init_strings() {
    HOO_LOG_LEVELS[0] = HOO_LOG_ERROR_TEXT;
    HOO_LOG_LEVELS[1] = HOO_LOG_DEBUG_TEXT;
    HOO_LOG_LEVELS[2] = HOO_LOG_INFO_TEXT;
}

void hclog_init(char* filename) {
    hclog_init_strings();
    pLogFile = fopen(filename, "w");
    if (0 == pLogFile) {
        pLogFile = stderr;
    }
}

void hclog_init_file(FILE* file) {
    hclog_init_strings();
    pLogFile = file;
    if (0 == pLogFile) {
        pLogFile = stderr;
    }
}

void hclog_log(const char* module, int level, const char* file, const char* func, int line, const char* message) {
	struct tm* t = 0;
	char datestring[256];
	const char* level_string;

    time_t tme;
    time(&tme);
    t = localtime(&tme);    
    
    strftime(datestring, 256, "%Y-%m-%d %T", t);
    if ((HOO_LOG_LEVEL_ERROR <= level) && (HOO_LOG_LEVEL_INFO >= level)) {
        level_string = (const char*) HOO_LOG_LEVELS[level];
    } else {
        level_string = (const char*) HOO_LOG_LEVEL_ERROR;
    }

    fprintf(pLogFile, "\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%d\',\'%s\'\n",
            datestring, module, level_string, file, func, line, message);
}
